#include <iostream>
#include <unistd.h>
#include <signal.h>

int exitFlag = 0;//退出标记位默认设置为0。

void printPending(sigset_t pending)
{
    for (int i = 32; i > 0; i--)
    {
        if (sigismember(&pending, i))
            std::cout << 1;
        else
            std::cout << 0;
    }
    std::cout << std::endl;
}
// 当前如果正在对n号进程进行处理，则自动会对该信号进行屏蔽；
// 当处理完成n信号时，才会解除对n号信号的屏蔽！
void handler(int sig)
{
    std::cout << "get a sig " << sig << std::endl;
    int count = 10;
    sigset_t pending;
    while (count)
    {
        std::cout << sig << " is being treated...the pending is: ";
        sigpending(&pending);
        printPending(pending);
        //count--;

        sleep(1);
    }
    exitFlag = 1;
}
int main()
{
    // 对2号信号进行捕获：
    struct sigaction act, oldact;
    act.sa_flags = 0;
    act.sa_handler = handler;
    sigemptyset(&act.sa_mask);

    //如果你想在处理某个信号时，对其他信号也进行屏蔽，就对该参数进行具体的设置即可：
    for(int i = 1; i<=31; i++) sigaddset(&act.sa_mask, i);
    sigaction(2, &act, &oldact);

    while (true)
    {
        if(exitFlag == 0)
            std::cout << "Hello Linux! my pid is " << getpid() << "..." << std::endl;
        else
        {
            sigset_t pending;
            std::cout << "process " << getpid() << " exit! the pending is: ";
            sigpending(&pending);
            printPending(pending);
            break;
        }
        sleep(1);
    }   
    return 0;
}